経時データのような縦長データから表形式の横長データへ相互変換
# 縦長データの例
data(Orthodont, package = "nlme") # 少年?少女の下顎枝データ
d <- Orthodont
head(d)
## distance age Subject Sex
## 1 26.0 8 M01 Male
## 2 25.0 10 M01 Male
## 3 29.0 12 M01 Male
## 4 31.0 14 M01 Male
## 5 21.5 8 M02 Male
## 6 22.5 10 M02 Male
# 縦長から横長へ変換
d.wide <- reshape(d, timevar = "age", idvar = c("Subject", "Sex"), direction = "wide")
head(d.wide)
## Subject Sex distance.8 distance.10 distance.12 distance.14
## 1 M01 Male 26.0 25.0 29.0 31.0
## 5 M02 Male 21.5 22.5 23.0 26.5
## 9 M03 Male 23.0 22.5 24.0 27.5
## 13 M04 Male 25.5 27.5 26.5 27.0
## 17 M05 Male 20.0 23.5 22.5 26.0
## 21 M06 Male 24.5 25.5 27.0 28.5
# 横長から縦長へ変換
vname <- names(d.wide)[grep("distance", names(d.wide))]
d.long <- reshape(d.wide, direction = "long", varying = vname, timevar = "age")
d.long <- d.long[order(d.long$id), ]
head(d.long)
## Subject Sex age distance id
## 1.8 M01 Male 8 26.0 1
## 1.10 M01 Male 10 25.0 1
## 1.12 M01 Male 12 29.0 1
## 1.14 M01 Male 14 31.0 1
## 2.8 M02 Male 8 21.5 2
## 2.10 M02 Male 10 22.5 2